package ru.ifmo.filemanager.filesystem.requests;

import static java.util.Arrays.sort;
import static ru.ifmo.filemanager.core.Core.error;

import java.io.IOException;

import ru.ifmo.filemanager.core.Core;
import ru.ifmo.filemanager.filesystem.FileSystem;
import ru.ifmo.filemanager.filesystem.interfaces.Directory;
import ru.ifmo.filemanager.filesystem.interfaces.DirectoryListReceiver;

public class ChangeDirectoryRequest extends Request implements DirectoryListReceiver, Runnable {
	
	private Directory directory;
	private int level;
	private String list[];

	public ChangeDirectoryRequest changeDirectory(Directory directory, int level) {
		this.directory = directory;
		this.level = level;
		directory.listAsync(this);
		return this;
	}

	public void directoryListSuccess(Directory self, String[] result) {
		if (cancelled) {
			return;
		}
		sort(result);
		list = result;
		Core.execute(this);
	}

	public void directoryListFailure(Directory self, IOException error) {
		if (cancelled) {
			return;
		}
		error("Cannot list directory", error, false);
		cancel();
	}

	public void run() {
		if (cancelled) {
			return;
		}
		FileSystem.setDirectory(directory, level, list);
		FileSystem.setCurrentRequest(null);
	}
}
